package com.laoda.ikun_food.controller.admin.rest;

import at.favre.lib.crypto.bcrypt.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laoda.ikun_food.entity.Admin;
import com.laoda.ikun_food.service.AdminService;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/admin")
@AllArgsConstructor
public class AdminRestController {

    private final AdminService adminService;

    @PostMapping("/login")
    public String processLogin(
            @RequestParam(name="adminname") String adminname,
            @RequestParam(name="password") String password,
            HttpSession session){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("adminname", adminname);
        var adminDB = adminService.getOne(queryWrapper);
        if(adminDB != null){
            // 使用BCrypt判断前端传入的password是否和数据库中加密的数据匹配
            var result =  BCrypt.verifyer().verify(password.toCharArray(), adminDB.getPassword());
            if(result.verified){
                session.setAttribute("admin", adminDB);
                return "ok";
            }
            return "用户名或密码错";
        }
        return "用户名或密码错";
    }

    @PostMapping("/logout")
    public String logout(HttpSession session){
//        session.removeAttribute("admin"); // 只是在当前会话中移除admin对象，会话仍然保持
        session.invalidate(); // 使当前会话失效
        return "ok";
    }
}
